﻿using AutoMapper;
using MediatR;
using TaskProject.Application.Command.BOM;
using TaskProject.Domain.BOM;
using TaskProject.ErrorCode;
using TaskProject.InfrasIntructure.Implement;
using TaskProject.InfrasIntructure.Interface;

namespace TaskProject.Application.Handler.BOM
{
    public class UpdateBOMHandler : IRequestHandler<UpdateBOMCommand, APIResult<int>>
    {
       IMapper mapper;
        DatabaseContext db;

        public UpdateBOMHandler(IMapper mapper, DatabaseContext db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<APIResult<int>> Handle(UpdateBOMCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var productExits = await db.sqlSugar.Queryable<ProductModel>().Where(c => c.ProductId == request.ProductId && !c.IsDel).AnyAsync(cancellationToken);
            if (!productExits)
            {
                res.Code = APIEnum.Fail;
                res.Msg = "产品不存在";
                return res;
            }
            if (request.Materials == null || !request.Materials.Any())
            {
                res.Code = APIEnum.Fail;
                res.Msg = "请至少选择一个物料";
                return res;
            }
            var MaterialIds = request.Materials.Select(m => m.MaterialId).ToList();
            var MaterialExits = await db.sqlSugar.Queryable<MaterialModel>().Where(c => MaterialIds.Contains(c.MaterialId) && !c.IsDel).ToListAsync(cancellationToken);
            if (MaterialExits.Count != MaterialIds.Count)
            {
                var missingIds = MaterialIds.Except(MaterialExits.Select(m => m.MaterialId)).ToList();
                res.Code = APIEnum.Fail;
                res.Msg = $"物料不存在{string.Join(",", missingIds)}";
                return res;
            }
        
          

            try
            {
                // 6. 删除原有的BOM记录
                await db.sqlSugar.Deleteable<BOMModel>().Where(c => c.ProductId == request.ProductId).ExecuteCommandAsync(cancellationToken);

                // 7. 创建新的BOM记录
                var bomsTolist = new List<BOMModel>();
                foreach (var materialId in request.Materials)
                {
                    var model = mapper.Map<BOMModel>(request);
                    model.BOMId = request.BOMId; // 使用原来的BOMId
                    model.MaterialId = materialId.MaterialId;
                    model.PartNum = materialId.PartNum;
                    model.LossRate = materialId.LossRate;
                    model.BOMState = model.BOMState == true ? false : model.BOMState;
                    model.IsDel = false;
                    model.CreteName = "李四";
                    model.CreteDate= DateTime.Now;
                    model.CreateDesc = "李四修改了一条记录";
                    bomsTolist.Add(model);
                }

                int r = await db.sqlSugar.Insertable(bomsTolist).ExecuteCommandAsync(cancellationToken);

                res.Msg = "BOM修改成功";
                res.Code = APIEnum.Success;
                res.Data = r;
            }
            catch (Exception ex)
            {
                res.Code = APIEnum.Fail;
                res.Msg = $"修改失败：{ex.Message}";
            }

            return res;
        }

    }
}
